// pages/showSingeVoteResult/showSingleVoteResult.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    voteId: '',
    voteBoxTitle: '',

    votingStateTagColor: 'rgb(77, 160, 77)',
    votingStateTagTxt: '进行中',

      isMultipleChoiceTagTxt: '',
      
      voteBoxDesc: '',
      optionList: [],
      startDateAndTime: '',

      currentTime: '',
      selectedOptionList: [],
      userId: '',

      pdfURL:'',

      // blockHeight:'',
      // tranctionId:'',

      isDisabled: false,

      endDateAndTime:'',

      // haveStartedVoteFlag: true,
      
  },

  onLoad(options){



      let voteId = options.voteId;
      let isMultipleChoice = wx.getStorageSync('isMultipleChoice');
      let startDateAndTime = wx.getStorageSync('startDateAndTime');

      this.setData({
        voteId: voteId,
        isMultipleChoiceTagTxt: isMultipleChoice?'多选':'单选',
        startDateAndTime: startDateAndTime,
      })

      // let type = options.type;
      // if(type == 2){
      //   this.setData({
      //     isDisabled: true,
      //     fromAddVoteBoxVoter: false,
      //   })
      // }

      // let startDateAndTimeArray = this.data.startDateAndTime.split(' ');
      // if(this.checkExpiredWithoutSecond(startDateAndTimeArray) == false){ // 投票未开始
      //   this.setData({
      //     votingStateTagColor: 'rgb(110, 20, 50)',
      //     votingStateTagTxt: '未开始',
      //     isDisabled: true,
      //     haveStartedVoteFlag: false,
      //   })
      //   let self = this;
      //   setTimeout(function () {
      //     self.setData({
      //       votingStateTagColor: 'rgb(77, 160, 77)',
      //       votingStateTagTxt: '进行中',
      //       isDisabled: false,
      //       haveStartedVoteFlag: true,
      //     })
      //   }, 10000)
      // }

      let self = this;
      wx.request({
        
       url: "https://www.intohash.com/vote_backend/vote/queryVoteInfo/" + voteId,
      //  url: "http://localhost:8001/vote_backend/vote/queryVoteInfo/" + voteId,
        method:"GET",
        
        success: function(e){
          console.log(e);
          let voteBoxTitle = e.data.data.title;
          let voteBoxDesc = e.data.data.voteDesc;
          let optionList = e.data.data.optionList;
          let endDateAndTime = e.data.data.rule.endDate;
          self.setData({
            voteBoxTitle: voteBoxTitle,
            voteBoxDesc: voteBoxDesc,
            optionList: optionList,
            endDateAndTime: endDateAndTime,
          })

          // let startDateAndTimeArray = self.data.startDateAndTime.split(' ');
          let endDateAndTimeArray = self.data.endDateAndTime.split(' ');
         // console.log(startDateAndTimeArray);
          console.log(endDateAndTimeArray);

          if(self.checkExpired(endDateAndTimeArray) == true){ // 投票已结束
            self.setData({
              votingStateTagColor: 'rgb(165, 165, 165)',
              votingStateTagTxt: '已结束',
              isDisabled : true
            })
          }

        },
        fail: function(e){
          console.error(e);
        }
      })  
  },
  
  // 时间校验函数：年-月-日 时:分:秒
  checkExpired(endDate) {
    const now = new Date();
    const endDateArray = endDate[0].split('-') // 将字符串分割成字符数组，分隔符为-
    const endYear = Number(endDateArray[0]) // 取字符数组中的年份，并将数据类型转换为number
    const endMonth = Number(endDateArray[1]) // 取字符数组中的月份，并将数据类型转换为number
    const endDay = Number(endDateArray[2]) // 取字符数组中的日期，并将数据类型转换为number

    const endDateArray2 = endDate[1].split(':') 
    const endHour = Number(endDateArray2[0]) 
    const endMinute = Number(endDateArray2[1]) 
    const endSecond = Number(endDateArray2[2]) 

    const time = new Date(endYear,endMonth-1,endDay,endHour,endMinute,endSecond);
    console.log('now',now)
    console.log('time',time)
    if(now>time){
      console.log('未过期')
      return true;
    }else{
      console.log('已过期')
      return false;
    }
  },

    // 时间校验函数：年-月-日 时:分
  checkExpiredWithoutSecond(endDate) {
    const now = new Date();
    const endDateArray = endDate[0].split('-') // 将字符串分割成字符数组，分隔符为-
    const endYear = Number(endDateArray[0]) // 取字符数组中的年份，并将数据类型转换为number
    const endMonth = Number(endDateArray[1]) // 取字符数组中的月份，并将数据类型转换为number
    const endDay = Number(endDateArray[2]) // 取字符数组中的日期，并将数据类型转换为number

    const endDateArray2 = endDate[1].split(':') 
    const endHour = Number(endDateArray2[0]) 
    const endMinute = Number(endDateArray2[1]) 

    const time = new Date(endYear,endMonth-1,endDay,endHour,endMinute);
    console.log('now',now)
    console.log('time',time)
    if(now>time){
      console.log('未过期')
      return true;
    }else{
      console.log('已过期')
      return false;
    }
  },


  onTapScanBtn(){
    wx.scanCode({
      onlyFromCamera: false,

      success: (res) => { // 扫一扫成功

        wx.showLoading({
          title: '投票中...',
          mask:true
        })

        console.log(res);

        try {

          let selectedOptionInfo = res.result.substring(14, res.result.length-1).split(',');

          const now = new Date();
          const nowYear = now.getFullYear();
          const nowMonth = now.getMonth()+1;
          const nowDay = now.getDate();
          const nowHour = now.getHours();
          const nowMinute = now.getMinutes();
          const nowSecond = now.getSeconds();
  
          const  currentTime = nowYear +
          '-' +
          ((nowMonth < 10) ? ('0' + nowMonth) : nowMonth) +
          '-' +
          ((nowDay < 10) ? ('0' + nowDay) : nowDay) +
          
          ' ' +
  
           ((nowHour < 10)?('0' + nowHour) : nowHour) +
          ':' +
          ((nowMinute < 10)?('0' + nowMinute) : nowMinute) +
          ':' +
          ((nowSecond < 10)?('0' + nowSecond) : nowSecond)  ;
  
          // let currentTime = (selectedOptionInfo[5].split('='))[1];
  
          let optionId = (selectedOptionInfo[1].split('='))[1];
          let newSelectedOptionList = [];
          newSelectedOptionList.push(optionId);
          let userId = (selectedOptionInfo[0].split('='))[1];
          let voteId = (selectedOptionInfo[2].split('='))[1];
  
          console.log(currentTime);
          console.log(newSelectedOptionList);
          console.log(userId);
          console.log(voteId);
  
          this.setData({
            currentTime: currentTime,
            selectedOptionList: newSelectedOptionList,
            // optionId: optionId,
            userId: userId,
            voteId: voteId,
          })
  
          let self = this;
  
          wx.request({
           url: "https://www.intohash.com/vote_backend/vote_user/vote",
            // url: "http://localhost:8001/vote_backend/vote_user/vote",
            method:"POST",
            data:{
              "currentTime": this.data.currentTime,
              "optionList": this.data.selectedOptionList,
              "userId": this.data.userId,
              "voteId": this.data.voteId,
  
            },   
            success: function(e){
  
              wx.hideLoading();
  
              console.log(e);
  
              if(e.data.success == true){ 
                console.log("合约调用成功");
                wx.showToast({  
                  title: "投票成功",   
                  icon: 'none'  
                })
  
              // wx.request({   
              //   url: "https://yinyuan.luowq.cn/vote_backend/vote/queryVoteDetail/" + voteId,
              //   // url: "http://localhost:8001/vote_backend/vote/queryVoteDetail/" + voteId,
              //   method:"GET",
              //   data: {
              //     "userId" : self.data.userId,
              //   },
              //   success: function(e){
              //     console.log(e);
              //     self.setData({
              //       blockHeight: e.data.data.voteDetails[0].voteBlockChain.blockHeight,
              //       tranctionId: e.data.data.voteDetails[0].voteBlockChain.transactionId,
              //     })
              //     wx.setClipboardData({ // 将blcokHeight和tranctionId复制到粘贴板
              //       data: "blcokHeight: " + self.data.blockHeight + ", tranctionId: " + self.data.tranctionId,
              //       success: function(res){
              //             wx.showToast({
              //               title: '复制成功',
              //             })
              //       },
              //       fail: function(res){
              //         wx.showToast({
              //           title: '复制失败',
              //         })
              //       }
              //     })
              //   },
              //   fail: function(e){
              //     console.error(e);
              //   }
              // })
  
  
              // 用户投完票后，更新选项中的票数
              wx.request({  
               url: "https://www.intohash.com/vote_backend/vote/queryVoteInfo/" + voteId,
              //  url: "http://localhost:8001/vote_backend/vote/queryVoteInfo/" + voteId,
                method:"GET",
                success: function(e){
                  console.log(e);
                  let newOptionList = e.data.data.optionList;
                  self.setData({
                    optionList: newOptionList,
                  })
                },
                fail: function(e){
                  console.error(e);
                }
              })
  
            }
            else{ 
              if(e.data.message == '合约调用失败'){ // 合约调用失败
                console.log("合约调用失败");
                wx.showToast({  
                  title: "投票未成功",   
                  icon: 'none'  
                })
              }
              else if(e.data.message == '已投过票或投票为开始'){ // 已投过票或投票未开始
                console.log("已投过票或投票未开始");
                wx.showToast({  
                  title: "选择无效",   
                  icon: 'none'  
                })
                // let startDateAndTimeArray = self.data.startDateAndTime.split(' ');
                // console.log(startDateAndTimeArray);
                // if(self.checkExpiredWithoutSecond(startDateAndTimeArray) == false){ // 投票未开始
                //   wx.showToast({  
                //         title: "投票未开始",   
                //         icon: 'none'  
                //       })
                //   }
                // else{ // 投票已开始
                //   wx.showToast({  
                //     title: "请扫描有效的二维码",   
                //     icon: 'none'  
                //   })
                // }
              }
            }
            },
            fail: function(e){
  
              wx.hideLoading();
  
              console.error(e);
  
              wx.showToast({  
                title: "投票未成功",   
                icon: 'none'  
              })
            }
          })    
        
        } catch (error) {
          console.log(error);
          wx.showToast({  
            title: "请扫描有效的二维码",   
            icon: 'none'  
          })
        }
    
      },
      fail: (res) => { // 扫一扫失败
         // console.log(res);
        // console.log("扫描二维码失败");
        // wx.showToast({  
        //   title: "扫描二维码失败",   
        //   icon: 'none'  
        // })
      }
    })
  },

  onTapCopyPdfURLBtn(){
    let voteId = this.data.voteId;
    let self = this;
  wx.request({
    url: "https://www.intohash.com/vote_backend/main/creatPdf/" + voteId,
    //  url: "http://localhost:8001/vote_backend/main/creatPdf/" + voteId,
    method:"get",

    success: function(e){
      console.log(e);
      if(e.data.success){
      
      console.log("成功获得投票用纸的URL");
      
     let pdfURL = e.data.data;
      self.setData({
        pdfURL: pdfURL,
      })

      wx.setClipboardData({ // 将pdfURL复制到粘贴板
        data: self.data.pdfURL,
        success: function(res){
          wx.showToast({
            title: '复制成功',
          })
        },
        fail: function(res){
          wx.showToast({
            title: '复制失败',
          })
        }
      })
    }
    else{
      console.log("未成功获得投票用纸的URL");
      wx.showToast({  
        title: "未成功获得投票用纸的URL",   
        icon: 'none'  
      })
    }
    },
    fail: function(e){
      console.log("未成功获得投票用纸的URL");
      wx.showToast({  
        title: "未成功获得投票用纸的URL",   
        icon: 'none'  
      })
      console.error(e);
    }
  })
  

  },

  onTapStopBtn(){

    let self = this;
    wx.showModal({

      title: '停止投票',
 
      content: '您确定要停止投票吗？',
 
      success: function (res) {
 
        if (res.confirm) {//这里是点击了确定以后
          self.setData({
            votingStateTagColor: 'rgb(165, 165, 165)',
            votingStateTagTxt: '已结束',
            isDisabled : true
          })

          let voteId = self.data.voteId;
          wx.request({
            url: "https://www.intohash.com/vote_backend/user/endBoxVote/" + voteId,
            //  url: "http://localhost:8001/vote_backend/user/endBoxVote/" + voteId,
            method:"post",
        
            success: function(e){
              console.log(e);
              console.log("结束投票箱投票");
            
            },
            fail: function(e){

            }
          })



        } else {//这里是点击了取消以后

        }
      },
      fail:function(res){

      }
    })
  }
 
})